package com.rabbitmq.exec.hello;

import com.rabbitmq.client.*;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

/**
 * @Description
 * @Author lhj
 * @Date 2024/4/13 15:59
 */
public class Consumer {
    static final Logger logger = LoggerFactory.getLogger(Consumer.class);
    public static final String QUEUE_NAME = "hello";
    
    public static void main(String[] args) throws IOException, TimeoutException {
        
        ConnectionFactory connectionFactory = new ConnectionFactory();
        connectionFactory.setHost("192.168.56.10");
        connectionFactory.setUsername("admin");
        connectionFactory.setPassword("123");
        Connection connection = connectionFactory.newConnection();
        Channel channel = connection.createChannel();
        logger.info("等待接收{}队列的消息", QUEUE_NAME);
        DeliverCallback deliverCallback = (consumerTag, message) -> {
            String msg = new String(message.getBody(), "UTF-8");
            logger.info("接收到{}队列的消息: {}, 消息标记: {}", QUEUE_NAME, msg, consumerTag);
        };
        
        CancelCallback cancelCallback = (consumerTag) -> {
            logger.error("消息者取消消费, 消息标记: {}", consumerTag);
        };

        /**
         * 消费者消费消息
         * 1. 消费哪个消息
         * 2. 消费成功之后是否要自动应答 true 代表自动应答 false 手动应答
         * 3. 消费者未成功消费的回调
         */
        channel.basicConsume(QUEUE_NAME,true, deliverCallback, cancelCallback);
    }
    
}
